
import {sinceCount} from '@/utils/util'
import { openDownloadDialog, sheet2blob} from "@/utils/util"
import {listAllBizProductionProcess} from '@/api/biz/bizProductionProcess';
const ListMixin = {
    data(){
        return {
          downLoading:false,
        }
    },
    created(){

    },
    methods: {
        
    /**
     * @table的合计 使用此方法请将pageSize 改为11，但是请求接口为10
     * @param {Array} columns table的列
     * @param {Array} dataSource table的数据
     */
    tableAddTotalRow (columns, dataSource) {
        columns = this.parseColumns(columns)
        //分页条数为11、21、31等的时候增加合计行
        let numKey = 'rowIndex'
        let totalRow = { [columns[0].dataIndex]: '合计' } 
        //需要合计的列
        let parseCols ='number,assistNumberA,assistNumberB,openingNumber,amount,'
        +'saleAmount,collectedAmount,unCollectedAmount,totalAmount,payAmount,hasAmount,salary,'
        +'processVol,installDeduct,installAmount,productNumber,unitPrice,price,'
        +'inventoryState,receivedNumber'
        parseCols = parseCols.split(',')
        columns.forEach(column => {
          let { key, dataIndex } = column
          if (![key, dataIndex].includes(columns[0].dataIndex)) {
            let total = 0
            // 是否有原始customRender
            let falg = typeof(column.customRender) === 'function'
            dataSource.forEach((data,index) => {
              if (parseCols.indexOf(dataIndex) > -1) {
                // 是数字且没有自定义渲染，没有自定义返回函数
                if(!isNaN(data[dataIndex]) && typeof(column.customRender) !== 'function' && typeof(column.scopedSlots)==="undefined"){
                  column.customRender = (t,r,i)=>{
                    return sinceCount(t)
                  }
                }
                if (data[dataIndex]) {
                  total += Number.parseFloat(data[dataIndex])
                } else {
                  total += 0
                }
              } else {
                total = '-'
              }
            })
            if (total !== '-') {
              total = total.toFixed(2)
            }
            totalRow[dataIndex] = total
          }
        })
      if (dataSource.length > 0 && this.queryParam.pageSize % 2 === 1) {
        dataSource.push(totalRow)
        //总数要增加合计的行数，每页都有一行合计，所以总数要加上
        let size = Math.ceil(this.queryParam.total / (this.queryParam.pageSize - 1))
        // this.queryParam.total = this.queryParam.total + size
      }
    },
    // 扁平化columns
    parseColumns(columns = []){
      let newColumns = []
      columns.forEach(val=>{
        if (!val.children || !val.children.length) {
          newColumns.push(val)
        }else{
          val.children.forEach(v=>{
            newColumns.push(v)
          })
        }
      })
      return newColumns
    },
    getQueryParam(){
      return Object.assign({},this.queryParam,{pageSize:this.queryParam.pageSize - 1})
    },
    /**
     * 禁用table选择框
     * @param {obj} record 
     */
     getCheckboxProps(record) {
      return { props: { disabled: record[this.columns[0].dataIndex] === '合计' } }
    },
    
    print() {
      this.printUrl=this.printUrlPath+"&r="+Math.random();
      if(this.purchaseDate && this.purchaseDate.length>0) {
        this.printUrl+="&startDate="+this.purchaseDate[0].format('yyyy-MM-DD');
      }
      if(this.purchaseDate && this.purchaseDate.length>1) {
        this.printUrl+="&endDate="+this.purchaseDate[0].format('yyyy-MM-DD');
      }
      if(this.queryParam.creator) {
        this.printUrl+="&creator="+this.queryParam.creator;
      }
      this.open=true;
    },
    async exportExcel() {
      let aoa = [this.columns.map(v=>v.title)]
      this.downLoading = true
      // 获取要导出的数据
      let dataSource = await this.loadAllData(1)
      this.downLoading = false
      for (let i = 0; i < dataSource.length; i++) {
        let item = []
        for (let l = 0; l < this.columns.length; l++) {
          let column = this.columns[l]
          if(column.dataIndex !== 'rowIndex'){
            let text = dataSource[i][column.dataIndex] || ''
            // 有自定义方法
            if(typeof(column.customRender) ==="function"){
              let res = column.customRender(text,dataSource[i])
              // 返回的是node节点
              if(res && typeof(res.componentOptions)!="undefined"){
                text = res.componentOptions.children[0].text
              }else{
                text = res || ''
              }
            }
            item.push(text)
          }
        }
        aoa.push(item)
      }
      let sheetName = this.title +'_'+ ((new Date()).getTime())
      openDownloadDialog(sheet2blob(aoa), sheetName)
    },
    loadAllData(){
      return new Promise((resolve, reject) => {
        let param = this.getQueryParam()
        param.pageSize = this.total
        this.listFunc(param).then(res=>{
          if(res.code == 200) {
            resolve(res.data.list || [])
          }else{
            this.message.error(res.msg)
            reject(res.msg)
          }
        })
      })
    },
    getProcessList(){
      return new Promise((resolve, reject) => {
        listAllBizProductionProcess().then(res=>{
          if(res.code == 200) {
            resolve(res.data)
          }else{
            this.message.error(res.msg)
            reject()
          }
        })
      })
    }
  },

}
export default ListMixin